from Map import Map
from pygame import Rect
from players import Player, Team
from Ball import Ball

class Field:
	""" Interface for all the field data. Anything involving the field should be placed here.
	"""
	def __init__(self, get_mode):
		self.tile_size = (25,25)
		self.map = Map((26,15), 3)
		self.rect = Rect( 10, 10, self.tile_size[0]*self.map.shape[0],
								  self.tile_size[1]*self.map.shape[1])
		self.ball = Ball((13,7))
		self.selected = None
		self.get_mode = get_mode
		
		#======== TEMP ===============
		self.teams = []
		self.teams.append(Team('home'))
		self.teams.append(Team('away'))
		self.teams[0].make_stock_team()
		self.teams[1].make_stock_team()
		self.build_path_map()
		#=======Remove=================
	
	def _get_field(self):
		return self
	
	def click(self, loc):
		field_loc = ((loc[0]-self.rect.x)/self.tile_size[0],(loc[1]-self.rect.y)/self.tile_size[1])
		print "clicked on field: ", field_loc
		if not self.selected:
			found = self.check_for_player(field_loc)
			if found:
				print "found player"
				self.selected = found
				self.get_mode(set = 'move')
		else:
			current_mode = self.get_mode()
			print "already have a selected player and the mode is: ", current_mode
			if current_mode == 'move':
				if self.selected.is_adj(field_loc):
					print 'moving player'
					self.selected.move_to(field_loc)
				else:
					self.selected = None
					self.get_mode(set=None)
			elif current_mode == 'hit':
				print "trying to hit player @ ", field_loc
				if self.selected.is_adj(field_loc):
					target = self.check_for_player(field_loc)
					if target:
						print self.selected, " wants to hit ", target
					else:
						print "no target there cant hit"
				else:
					self.selected = None
					self.get_mode(set=None)
		
	def set_ball_loc(self, loc):
		""" Sets the locaton of the ball to the tuple loc = (x,y)
		"""
		self.ball.loc = loc
		
	def build_path_map(self):
		""" Builds the map for the pathfinding. This member takes the position of all 
			the players on the field and adds their tackle zones to all the adj positions.
			The implementation of the pathfinding algo will prefer the lower numbers.
		
		t_points = []
		for p in self.players:
			for l in p.get_adj():
				t_points.append(l)
		for tp in t_points:
			self.map.set_at(tp, 0)
		for tp in t_points:
			old = self.map.get_at(tp)
			new = old + 1
			self.map.set_at(tp, new)
		"""
		pass	
			
	def check_for_player(self,loc):
		""" Checks the list of players to see if any of them are at the loc.
			returns the player on found or None
		"""
		for t in self.teams:
			for p in t.players:
				if p.loc == loc:
					return p
		return None
				
